<template>
  <el-tree-select
    v-model="selectCategoryId"
    :data="categoryList"
    :props="defaultProps"
    :multiple="multiple"
    :show-checkbox="multiple"
    :placeholder="placeholder"
    class="w-100%"
    node-key="id"
    default-expand-all
    check-strictly
    filterable
    clearable
  />
</template>
<script lang="ts" setup>
import { defaultProps, handleTree } from '@/utils/tree'
import { oneOfType } from 'vue-types'
import { propTypes } from '@/utils/propTypes'
import { CategoryApi } from '@/api/universal/category'

/** 分类选择组件 */
defineOptions({ name: 'CategoryPicker' })

const props = defineProps({
  modelValue: oneOfType<number | number[] | string | string[]>([
    Number,
    Array<Number>,
    String,
    Array<String>
  ]),
  module: propTypes.string.def(''),
  identity: propTypes.string.def(''),
  placeholder: propTypes.string.def('请选择分类'),
  multiple: propTypes.bool.def(false),
  includeRoot: propTypes.bool.def(false),
  rootName: propTypes.string.def('顶级分类')
})

/** 选中的分类 ID */
const selectCategoryId = computed({
  get: () => {
    return props.modelValue
  },
  set: (val: number | number[]) => {
    emit('update:modelValue', val)
  }
})

/** 分类选择 */
const emit = defineEmits(['update:modelValue'])

/** 初始化 **/
const categoryList = ref<Tree[]>([]) // 分类树
onMounted(async () => {
  // 获得分类树
  categoryList.value = []
  const data = await CategoryApi.getCategorySimpleList(props.module, props.identity, {})
  if (props.includeRoot) {
    const root: Tree = { id: '0', name: props.rootName, children: [] }
    root.children = handleTree(data, 'id', 'parentId')
    categoryList.value.push(root)
  } else {
    categoryList.value = handleTree(data, 'id', 'parentId')
  }
})
</script>
